<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class InitDb extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // 统计建表用时
        $startTime = microtime(true);

        // 权限
        Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique()->comment('名称');
            $table->string('description')->nullable()->comment('说明');
            $table->timestamps();
        });

        // 管理员
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

        // 管理员权限关系
        Schema::create('admin_permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('admin_id')->comment('管理员id');
            $table->unsignedInteger('permission_id')->comment('权限id');

            $table->foreign('admin_id')->references('id')->on('admins')->onDelete('cascade');
            $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
        });

        // 管理员密码重置
        Schema::create('admin_password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at')->nullable();
        });

        // -------------------------------- cut --------------------------------------------

        // 用户
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

        // 用户密码重置
        Schema::create('user_password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at')->nullable();
        });

        $endTime = microtime(true);
        $elapsed = $endTime - $startTime;

        define('CREATE_TABLES_ELAPSED_TIME', $elapsed);

        echo "-------------------\n";
        echo "建表用时: $elapsed 秒\n";
        echo "-------------------\n";
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('user_password_resets');
        Schema::drop('users');
        Schema::drop('admin_password_resets');
        Schema::drop('admin_permissions');
        Schema::drop('admins');
        Schema::drop('permissions');
    }
}
